import iso8601
from flask import Blueprint, jsonify, request
from flask_jwt_extended import get_jwt_identity, jwt_required

from app import LogService
from app.models import Station
from app.models.ticket_lib import Ticket
from app.models.train_lib import Train
from presenter import StationPresenter
from presenter.ticket import TicketPresenter
from presenter.train import TrainPresenter
from utils import create_response, StateCode

query_bp = Blueprint('query', __name__)


@query_bp.route('/trains/query_train', methods=['GET'])
def queryTrains():  # 查询车次方法
    from_station = request.args.get('from')
    to_station = request.args.get('to')
    date = iso8601.parse_date(request.args.get('date'))
    if not from_station or not to_station or not date:
        return jsonify(create_response(StateCode.PARAMS_ERROR)), 400

    trains = Train.queryTrains(from_station, to_station, date)
    trains_presenters = [TrainPresenter(train).as_dict() for train in trains]
    LogService.log()
    return jsonify(create_response(StateCode.SUCCESS, data=trains_presenters)), 200


@query_bp.route('/tickets', methods=['GET'])
@jwt_required()
def getTickets():  # 查询车票方法
    current_user = get_jwt_identity()  # 解码JWT得到用户ID
    tickets = Ticket.query.filter_by(passenger_id=current_user).all()
    tickets_presenters = [TicketPresenter(ticket).as_dict() for ticket in tickets]
    LogService.log()
    return jsonify(create_response(StateCode.SUCCESS, data=tickets_presenters)), 200


@station_bp.route('/stations', methods=['GET'])
def queryStations():  # 查询站点方法
    stations = Station.query.all()
    stations_presenters = [StationPresenter(station).as_dict() for station in stations]
    LogService.log()
    return jsonify(create_response(StateCode.SUCCESS, data=stations_presenters)), 200
